import {
  DataItem,
  EndpointItem,
  EndpointParam,
  ServiceParam,
  TraceItem,
  DataParams,
  ServiceItem,
  InstanceItem,
  InstanceParams,
  TagValueParam,
  InstanceInfoParam,
  InstanceInfoItem,
} from './model/traceModel';
import { maintenanceHttp } from '../../../../utils/http/axios';
import { stampToDate } from '/@/utils/dateUtil';

enum Api {
  GET_TRACE_LIST = '/v1/maintenance/apm/queryBasicTraces',
  GET_TRACE_BY_ID = '/v1/maintenance/apm/queryTrace',
  GET_ALL_INSTANCE = '/v1/maintenance/apm/getServiceInstances',
  GET_SERVICE = '/v1/maintenance/apm/getAllServices',
  GET_ENDPOINT = '/v1/maintenance/apm/searchEndpoint',
  GET_TAG_VALUE = '/v1/maintenance/apm/queryTraceTagValues',
  GET_INSTANCE_INFO = '/v1/maintenance/apm/getInstanceAttributes',
}
//获取实例详情
export const getInstanceInfo = async (params: InstanceInfoParam) => {
  const res = await maintenanceHttp.get<InstanceInfoItem>({ url: Api.GET_INSTANCE_INFO, params });
  return res;
};
//获取服务
export const getService = async (params: ServiceParam) => {
  const res = await maintenanceHttp.post<ServiceItem[]>({ url: Api.GET_SERVICE, params });
  const result = res.map((item) => {
    return {
      label: item.label,
      value: item.key,
    };
  });
  return result;
};
//获取端点
export const getEndpoint = async (params: EndpointParam) => {
  const res = await maintenanceHttp.post<EndpointItem[]>({ url: Api.GET_ENDPOINT, params });
  const result = res.map((item) => {
    return {
      label: item.label,
      value: item.key,
    };
  });
  return result;
};
//获取tag的value
export const getTagValue = async (params: TagValueParam) => {
  const res = await maintenanceHttp.post<string[]>({ url: Api.GET_TAG_VALUE, params });
  const result = res.map((item) => {
    return {
      label: item,
      value: item,
    };
  });
  return result;
};
//获取trace导航列表
export const getBasicTraces = async (params: DataParams) => {
  const res = await maintenanceHttp.post<DataItem[]>({ url: Api.GET_TRACE_LIST, params });

  res.map((item) => {
    item.title = item.endpointNames[0];
    item.start = stampToDate(item.start);
    return item;
  });
  return res;
};
//根据traceId获取追踪信息
export const getTraceById = async (params: string) => {
  const _param = { traceId: params };
  const res = await maintenanceHttp.get<TraceItem[]>({ url: Api.GET_TRACE_BY_ID, params: _param });
  const result = res.map((item) => {
    item.nodeId = item.segmentId + '-' + item.spanId;
    item.daughter = [];
    return item;
  });
  return result;
};
//获取实例信息
export const getInstanceAttributes = async (params: InstanceParams) => {
  const res = await maintenanceHttp.post<InstanceItem[]>({ url: Api.GET_ALL_INSTANCE, params });
  const result = res.map((item) => {
    return {
      label: item.label,
      value: item.key,
    };
  });
  return result;
};
